using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SnakeMove : MonoBehaviour
{
    public Transform _snakePrefab;
    public List<GameObject> _bodyList = new List<GameObject>();
    private Vector2 _MoveTo = Vector2.right;
    public float _moveInterval = 0.3f; //移动速度
    private float _timer = 0;
    private bool _shouldGrow = false;
    private List<Vector3> _previousPositions = new List<Vector3>(); // 记录所有段的旧位置
    private Coroutine _speedBoostCoroutine; // 加速协程
    private int _initCount = 3;
    Vector2 _newMoveOn = new(0, 0);
    public GameObject _food;
    private bool _canChangeDirection = true;
    void Start()
    {
        _food.gameObject.SetActive(true);
        _bodyList.Add(this.gameObject);
        for (int i = 0; i < _initCount; i++) 
        {
            _newMoveOn.x = -1 - i;
            Transform body = Instantiate(_snakePrefab, _newMoveOn, Quaternion.identity);
            _bodyList.Add(body.gameObject);
        }
    }

    void Update()
    {
        // 检测按键方向
        if (Input.GetKeyDown(KeyCode.W) && _MoveTo != Vector2.down && _canChangeDirection)
        {
            _MoveTo = Vector2.up;
            _canChangeDirection = false;
        }
        else if (Input.GetKeyDown(KeyCode.S) && _MoveTo != Vector2.up && _canChangeDirection)
        {
            _MoveTo = Vector2.down;
            _canChangeDirection = false;
        }
        else if (Input.GetKeyDown(KeyCode.D) && _MoveTo != Vector2.left && _canChangeDirection)
        {
            _MoveTo = Vector2.right;
            _canChangeDirection = false;
        }
        else if (Input.GetKeyDown(KeyCode.A) && _MoveTo != Vector2.right && _canChangeDirection)
        {
            _MoveTo = Vector2.left;
            _canChangeDirection = false;
        }
           
        // 根据一定时间移动蛇的位置
        _timer += Time.deltaTime;
        if (_timer >= _moveInterval)
        {
            MoveToNextGrid();
            _timer = 0;
        }
    }
    // 移动到下一格的方法
    public void MoveToNextGrid()
    {
        //记录所有段的旧位置
        _previousPositions.Clear();
        for (int i = 0; i < _bodyList.Count; i++) 
        {
            if (_bodyList[i] == null) 
            {
                _bodyList.RemoveAt(i);
                i--;
                continue;
            }
            _previousPositions.Add(_bodyList[i].transform.position);
        }
        // 先移动头部到新位置
        transform.position = new Vector3(
            Mathf.Round(transform.position.x) + _MoveTo.x,
            Mathf.Round(transform.position.y) + _MoveTo.y,
            0.0f
        );
        // 再移动身体段到前一段的旧位置
        for (int i = 1; i < _bodyList.Count; i++)
        {
            _bodyList[i].transform.position = _previousPositions[i - 1];
        }
        // 最后尝试调用生成身体方法
        if (_shouldGrow) Grow();
        // 允许调整方向
        _canChangeDirection = true;
    }
    // 生成新的身体方法
    private void Grow()
    {
        // 生成位置始终为最后一个身体段的旧位置
        Vector3 spawnPosition = _previousPositions[^1];
        Transform body = Instantiate(_snakePrefab, spawnPosition, Quaternion.identity);
        _bodyList.Add(body.gameObject);
        _shouldGrow = false;
    }
    // 应用加速食物功能
    public void ApplySpeedBoost(float newInterval, float time) 
    {
        //如果已经有加速效果 移除并重新开启
        if (_speedBoostCoroutine != null)
        {
            _speedBoostCoroutine = null;
        }
        //调用加速协程
        _speedBoostCoroutine = StartCoroutine(SpeedBoostRoutine(newInterval, time));
    }
    // 加速功能协程方法
    private IEnumerator SpeedBoostRoutine(float newInterval, float time) 
    {
        // 记录旧速度
        float old_moveInterval = _moveInterval;
        _moveInterval = newInterval;
        _timer = 0;
        // 等待多少秒
        yield return new WaitForSeconds(time);
        // 回到原来的速度
        _moveInterval = old_moveInterval;
        _speedBoostCoroutine = null;
    }
    // 减少神身体数量方法
    public void CutSnakeBody() 
    {
        // 确定需要删除的数量，最多3
        int removeCount = Mathf.Min(3, _bodyList.Count - 1);
        for (int i = 0; i < removeCount; i++) 
        {
            // 确保每次删除的都是最后一个元素
            int lastIndex = _bodyList.Count - 1;
            GameObject.Destroy( _bodyList[lastIndex].gameObject );
            _bodyList.RemoveAt(lastIndex);
        }
    }
    // 碰撞检测
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Food"))
        {
            _shouldGrow = true;
        }
        else if (collision.CompareTag("Wall") || collision.CompareTag("Body") || collision.CompareTag("Obstacle"))
        {
            SceneManager.LoadScene("GameOver");
        }
    }
}